package cn.tedu.knows.sys.controller;


import cn.tedu.knows.commons.exception.ServiceException;
import cn.tedu.knows.commons.model.User;
import cn.tedu.knows.sys.service.IUserService;
import cn.tedu.knows.sys.vo.RegisterVo;
import cn.tedu.knows.sys.vo.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author tedu.cn
 * @since 2021-07-23
 */
@RestController
// 类上编写@RequestMapping表示
// 当前类中所有的控制器方法的请求路径要添加这里指定的前缀
@RequestMapping("/v1/users")
@Slf4j
public class UserController {

    @Autowired
    private IUserService userService;

    @GetMapping("/master")
    public List<User> getTeachers(){
        List<User> list=userService.getTeachers();
        return list;
    }

    @GetMapping("/me")
    public UserVo me(@AuthenticationPrincipal UserDetails user){
        UserVo userVo=userService.getCurrentUserVo(
                                        user.getUsername());
        return userVo;
    }

    //学生注册的控制器方法
    @PostMapping("/register")
    //@Validated表示启动SpringValidation框架对
    // RegisterVo参数进行验证,验证规则写在了RegisterVo类中
    // 在RegisterVo参数后紧跟一个BindingResult类型的参数
    // Spring Validation框架会吧验证结果保存到BindingResult对象中
    public String registerStudent(
            @Validated RegisterVo registerVo,
            BindingResult result) {
        log.debug("接收到表单信息:{}", registerVo);
        if (result.hasErrors()) {
            //从错误信息中获得详情
            String msg = result.getFieldError().getDefaultMessage();
            return msg;
        }
        try {
            userService.registerStudent(registerVo);
            return "注册完成";
        } catch (ServiceException e) {
            return e.getMessage();
        }
    }
}
